﻿namespace BM.Tools.WebControls.MForm.BlogExample
{
    using System;

    /// <summary>
    /// This page is used to perform changes on a single blog entry.
    /// </summary>
    public partial class BlogEntryCommandPage : System.Web.UI.Page
    {
        /// <summary>
        /// Gets the index of the blog entry in the <see cref="BlogEntries"/> collection.
        /// </summary>
        protected int Index
        {
            get
            {
                if (ViewState["index"] == null)
                {
                    ViewState["index"] = int.Parse(Request["index"]);                    
                }

                return (int)ViewState["index"];
            }
        }

        /// <summary>
        /// Sets the appropriate blog control mode and sets the BlogEntry object of the blog control.
        /// </summary>
        /// <param name="sender">
        /// The sender.
        /// </param>
        /// <param name="e">
        /// The event args.
        /// </param>
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                blogControl.Mode = (BlogControlMode)Enum.Parse(typeof(BlogControlMode), Request["command"]);
                if (blogControl.Mode != BlogControlMode.EntryAdding)
                {
                    blogControl.BlogEntry = BlogEntries.Get()[Index];
                }

                Page.DataBind();
            }
        }

        /// <summary>
        /// Saves the changes and redirects back to the Entries page
        /// </summary>
        /// <param name="sender">
        /// The sender.
        /// </param>
        /// <param name="e">
        /// The event args.
        /// </param>
        protected void Save(object sender, EventArgs e)
        {
            if (Page.IsValid)
            {
                var blogEntries = BlogEntries.Get();
                AddOrChangeBlogEntry(blogEntries);                
                blogEntries.Persist();
                Response.Redirect("Entries.aspx");
            }
        }

        private void AddOrChangeBlogEntry(BlogEntries blogEntries)
        {
            if (blogControl.Mode == BlogControlMode.EntryAdding)
            {
                blogEntries.Add(blogControl.BlogEntry);
            } 
            else
            {
                blogEntries[Index] = blogControl.BlogEntry;    
            }
        }
    }
}
